package cn.iocoder.yudao.module.dr.service.collection3dacquisition;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.dr.controller.admin.collection3dacquisition.vo.Collection3dAcquisitionPageReqVO;
import cn.iocoder.yudao.module.dr.controller.admin.collection3dacquisition.vo.Collection3dAcquisitionSaveReqVO;
import cn.iocoder.yudao.module.dr.controller.admin.collectionmanagement.vo.Collection3dExportExcelVO;
import cn.iocoder.yudao.module.dr.controller.admin.collectionmanagement.vo.Collection3dImportExcelVO;
import cn.iocoder.yudao.module.dr.controller.admin.collectionmanagement.vo.Collection3dImportIndexVO;
import cn.iocoder.yudao.module.dr.controller.admin.collectionmanagement.vo.CollectionImportRespVO;
import cn.iocoder.yudao.module.dr.dal.dataobject.collection3dacquisition.Collection3dAcquisitionDO;
import cn.iocoder.yudao.module.dr.dal.dataobject.collectionlinkaddress.CollectionLinkAddressDO;
import cn.iocoder.yudao.module.dr.dal.dataobject.collectionmanagement.CollectionManagementDO;
import cn.iocoder.yudao.module.dr.dal.mysql.collection3dacquisition.Collection3dAcquisitionMapper;
import cn.iocoder.yudao.module.dr.dal.mysql.collectionlinkaddress.CollectionLinkAddressMapper;
import cn.iocoder.yudao.module.dr.service.collectionmanagement.CollectionManagementService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.dr.enums.ErrorCodeConstants.COLLECTION3D_ACQUISITION_NOT_EXISTS;

/**
 * 藏品三维采集信息 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class Collection3dAcquisitionServiceImpl implements Collection3dAcquisitionService {

    @Resource
    private Collection3dAcquisitionMapper collection3dAcquisitionMapper;

    @Resource
    CollectionLinkAddressMapper collectionLinkAddressMapper;


    @Override
    public Long createCollection3dAcquisition(Collection3dAcquisitionSaveReqVO createReqVO) {
        // 插入
        Collection3dAcquisitionDO collection3dAcquisition = BeanUtils.toBean(createReqVO, Collection3dAcquisitionDO.class);
        collection3dAcquisitionMapper.insert(collection3dAcquisition);

        // 插入子表
        createReqVO.getCollectionLinkAddress().forEach(o -> o.setBizType("3"));
        createCollectionLinkAddressList(collection3dAcquisition.getId(), createReqVO.getCollectionLinkAddress());
        // 返回
        return collection3dAcquisition.getId();
    }

    @Override
    public void updateCollection3dAcquisition(Collection3dAcquisitionSaveReqVO updateReqVO) {
        // 校验存在
        validateCollection3dAcquisitionExists(updateReqVO.getId());
        // 更新
        Collection3dAcquisitionDO updateObj = BeanUtils.toBean(updateReqVO, Collection3dAcquisitionDO.class);
        // 更新子表
        updateReqVO.getCollectionLinkAddress().forEach(o -> o.setBizType("3"));
        updateCollectionLinkAddressList(updateReqVO.getId(),"3", updateReqVO.getCollectionLinkAddress());
        collection3dAcquisitionMapper.updateById(updateObj);
    }

    @Override
    public void deleteCollection3dAcquisition(Long id) {
        // 校验存在
        validateCollection3dAcquisitionExists(id);
        // 删除
        collection3dAcquisitionMapper.deleteById(id);
    }

    private void validateCollection3dAcquisitionExists(Long id) {
        if (collection3dAcquisitionMapper.selectById(id) == null) {
            throw exception(COLLECTION3D_ACQUISITION_NOT_EXISTS);
        }
    }

    @Override
    public Collection3dAcquisitionDO getCollection3dAcquisition(Long id) {
        return collection3dAcquisitionMapper.selectById(id);
    }

    @Override
    public PageResult<Collection3dAcquisitionDO> getCollection3dAcquisitionPage(Collection3dAcquisitionPageReqVO pageReqVO) {
        return collection3dAcquisitionMapper.selectPage(pageReqVO);
    }

    private void createCollectionLinkAddressList(Long collectionId, List<CollectionLinkAddressDO> list) {
        if(list == null || list.size() == 0) {
            return ;
        }
        list.forEach(o -> o.setCollectionId(collectionId));
        collectionLinkAddressMapper.insertBatch(list);
    }

    private void updateCollectionLinkAddressList(Long collectionId,String bizType, List<CollectionLinkAddressDO> list) {
        deleteCollectionLinkAddressByCollectionId(collectionId,bizType);
        if(list == null || list.size() == 0) {
            return ;
        }
        list.forEach(o -> o.setId(null).setUpdater(null).setUpdateTime(null)); // 解决更新情况下：1）id 冲突；2）updateTime 不更新
        createCollectionLinkAddressList(collectionId, list);
    }
    private void deleteCollectionLinkAddressByCollectionId(Long collectionId,String bizType) {
        collectionLinkAddressMapper.deleteByCollectionId(collectionId);
    }

    @Override
    public CollectionImportRespVO saveImportDataList(CollectionManagementService managementService, List<Collection3dImportIndexVO> dList, Boolean updateSupport, Integer importType) {

        CollectionImportRespVO respVO = CollectionImportRespVO.builder().createNames(new ArrayList<>())
                .updateNames(new ArrayList<>()).failureNames(new LinkedHashMap<>()).build();
        // 校验数据
        Collection3dAcquisitionDO collection3dAcquisitionDO ;
        for (Collection3dImportIndexVO d : dList) {
            collection3dAcquisitionDO = new Collection3dAcquisitionDO();

            CollectionManagementDO collectionManagement = managementService.selectByGeneralAccessionNumber(d.getGeneralAccessionNumber());
            if(Objects.isNull(collectionManagement)){
                respVO.getFailureNames().put(d.getResultName(), "藏品总登记号不存在");
                continue;
            }
            // 校验数据
            Collection3dAcquisitionDO exist = collection3dAcquisitionMapper.selectByResultName(collectionManagement.getId(),d.getResultName());
            if (exist != null) {
                if (updateSupport) {
                    collection3dAcquisitionDO = exist;
                    BeanUtils.copyProperties(d, collection3dAcquisitionDO);
                    collection3dAcquisitionDO.setCollectionId(collectionManagement.getId());
                    collection3dAcquisitionDO.setId(exist.getId());
                    collection3dAcquisitionMapper.updateById(collection3dAcquisitionDO);
                    respVO.getUpdateNames().add(d.getResultName());
                } else {
                    respVO.getFailureNames().put(d.getResultName(), "失败，文件名已存在");
                }
                continue;
            }
            // 插入或更新
            BeanUtils.copyProperties(d, collection3dAcquisitionDO);
            collection3dAcquisitionDO.setCollectionId(collectionManagement.getId());
            collection3dAcquisitionMapper.insert(collection3dAcquisitionDO);
            respVO.getCreateNames().add(d.getResultName());
        }
        return respVO;
    }

    @Override
    public void auditCollection3dAcquisition(Collection3dAcquisitionSaveReqVO updateReqVO) {
        LambdaUpdateWrapper<Collection3dAcquisitionDO> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(Collection3dAcquisitionDO::getId,updateReqVO.getId())
                .set(Collection3dAcquisitionDO::getCataloger,updateReqVO.getCataloger())
                .set(Collection3dAcquisitionDO::getSourceStatus,updateReqVO.getSourceStatus())
                .set(Collection3dAcquisitionDO::getCatalogDate,updateReqVO.getCatalogDate())
                .set(Collection3dAcquisitionDO::getAuditOpinion,updateReqVO.getAuditOpinion())
                .set(Collection3dAcquisitionDO::getSubmitAuditDate,updateReqVO.getSubmitAuditDate());
        collection3dAcquisitionMapper.update(null,updateWrapper);

    }
}